package fule.com.kotlindemo.adapter

import android.support.annotation.DrawableRes
import android.support.annotation.IdRes
import android.support.annotation.StringRes
import android.support.v7.widget.RecyclerView
import android.util.SparseArray
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView

@Suppress("UNCHECKED_CAST")
/**
 * Created by njb on 2016/12/27.
 */

class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    private val holder: SparseArray<View> = SparseArray()

    operator fun <V : View> get(@IdRes id: Int): V? {
        var view: View? = holder.get(id)
        if (view == null) {
            view = itemView.findViewById(id)
            holder.put(id, view)
        }
        return view as V?
    }

    private fun getTextView(@IdRes id: Int): TextView? {
        return get(id)
    }

    fun getButton(@IdRes id: Int): Button? {
        return get(id)
    }

    private fun getImageView(@IdRes id: Int): ImageView? {
        return get(id)
    }

    fun setTextView(@IdRes id: Int, charSequence: CharSequence) {
        if (getTextView(id) != null) {
            getTextView(id)!!.text = charSequence
        }
    }

    fun setTextView(@IdRes id: Int, @StringRes id2: Int) {
        if (getTextView(id) != null) {
            getTextView(id)!!.setText(id2)
        }
    }

    fun setImageView(@IdRes id: Int, @DrawableRes id2: Int) {
        if (getImageView(id) != null) {
            getImageView(id)!!.setImageResource(id2)
        }
    }
}